import React, { Component, useContext, useState, useEffect } from 'react'
import UseReducer from './useReducer'

export default class Test extends Component {

  render () {
    return (
      <div>
        <Toolbar />
      </div>
    )
  }
}

const themes = {
  light: {
    foreground: '#000000',
    background: 'yellow'
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222'
  }
}

const themeContext = React.createContext(themes.light)

function Toolbar () {
  const [param, setParam] = useState(themes.light)

  return (
    <themeContext.Provider value={param}>
      <button onClick={() => {
        setParam(themes.dark)
        const event = new CustomEvent('hpk', { detail: {} })
        window.dispatchEvent(event)
      }}>
        点击我
      </button>
      {
        param.background === '#222222' ? <ThemeButton /> : <UseReducer />
      }
    </themeContext.Provider>
  )
}

function ThemeButton () {
  const theme = useContext(themeContext)
  useEffect(() => {
    document.title = `go go go!`
    window.addEventListener('hpk', () => {
      console.log('我是监听器1')
    })
  })
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  )
}

function ThemeShow () {
  const theme = useContext(themeContext)
  useEffect(() => {
    document.title = `wait me!`
    window.addEventListener('hpk', () => {
      console.log('我是监听器2')
    })
  })
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      我是监听器2
    </button>
  )
}